import android.content.Context
import android.util.Log
import com.example.idlefish.HomeAndSearch.SearchRecord
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken

class SearchHistoryManager(context: Context) {

    private val prefs = context.getSharedPreferences("search_history_prefs", Context.MODE_PRIVATE)
    private val gson = Gson()
    private val MAX_HISTORY_COUNT = 30
    private val HISTORY_KEY = "search_history"

    // 保存历史记录
    fun saveSearchRecord(content: String) {
        // 加载当前的历史记录
        val currentHistory = loadSearchHistory().toMutableList()

        // 移除重复的记录（如果已存在）
        currentHistory.removeAll { it.content == content }

        // 添加新记录到开头
        currentHistory.add(0, SearchRecord(content, System.currentTimeMillis()))

        // 如果记录超过 30 条，删除最旧的记录
        if (currentHistory.size > MAX_HISTORY_COUNT) {
            currentHistory.subList(MAX_HISTORY_COUNT, currentHistory.size).clear()
        }

        // 将列表保存回 SharedPreferences
        val jsonString = gson.toJson(currentHistory)
        prefs.edit().putString(HISTORY_KEY, jsonString).apply()
    }

    // 加载历史记录

    fun loadSearchHistory(): MutableList<SearchRecord> {
        val jsonString = prefs.getString(HISTORY_KEY, null)
        return if (!jsonString.isNullOrEmpty()) {
            val type = object : TypeToken<List<SearchRecord>>() {}.type
            gson.fromJson<List<SearchRecord>>(jsonString, type).toMutableList() // 转换为 MutableList
        } else {
            mutableListOf() // 返回一个空的可变列表
        }
    }


    // 清空历史记录
    fun clearSearchHistory() {
        prefs.edit().remove(HISTORY_KEY).apply()
    }
    fun deleteSearchRecord(num: Int) {
        val currentHistory = loadSearchHistory().toMutableList()
        if (num >= 0 && num < currentHistory.size) {
            currentHistory.removeAt(num)
            val jsonString = gson.toJson(currentHistory)
            prefs.edit().putString(HISTORY_KEY, jsonString).apply()
        } else {
            Log.w("SearchHistory", "Invalid record number: $num")
        }
    }
}
